package com.zjun.demo.experimentaldemo.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RawRes;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

public class NotificationUtils {
    private static final String TAG = "NotificationUtils";
    private static final long MIN_SOUND_INTERVAL = 1000; // 最小声音间隔1秒
    private static long lastSoundTime = 0;

    /**
     * 创建通知渠道（Android 8.0+）
     */
    public static void createSoundChannel(Context context, String channelId,
                                          String channelName, @RawRes int soundResId) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResId);

            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();

            NotificationChannel channel = new NotificationChannel(
                    channelId,
                    channelName,
                    NotificationManager.IMPORTANCE_HIGH); // 必须使用HIGH

            channel.setSound(soundUri, audioAttributes);
            channel.setBypassDnd(true); // 绕过勿扰模式
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    /**
     * 显示带自定义声音的通知（优化版）
     */
    @SuppressLint("MissingPermission")
    public static void showSoundNotification(Context context, String channelId,
                                             String title, String content, int smallIcon, @RawRes int soundResId,
                                             PendingIntent pendingIntent) {

        // 1. 检查声音是否可以播放
        if (!canPlaySound(context)) {
            Log.w(TAG, "Cannot play sound - device is in silent/do not disturb mode");
            return;
        }

        // 2. 节流控制 - 避免声音过于频繁
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastSoundTime < MIN_SOUND_INTERVAL) {
            Log.w(TAG, "Sound throttled, too frequent");
            return;
        }
        lastSoundTime = currentTime;

        // 3. 获取音频焦点（可选）
        requestAudioFocus(context);

        // 4. 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(smallIcon)
                .setContentTitle(title)
                .setContentText(content)
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setCategory(NotificationCompat.CATEGORY_ALARM) // 提高优先级
                .setAutoCancel(true);

        // Android 7.1及以下直接设置声音
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResId);
            builder.setSound(soundUri);
        }

        if (pendingIntent != null) {
            builder.setContentIntent(pendingIntent);
        }

        // 5. 发送通知（使用唯一ID）
        int notificationId = generateUniqueId();
        NotificationManagerCompat.from(context).notify(notificationId, builder.build());

        // 6. 额外确保声音播放（针对某些厂商ROM）
        ensureSoundPlayback(context, soundResId);
    }

    /**
     * 检查是否可以播放声音
     */
    private static boolean canPlaySound(Context context) {
        // 检查勿扰模式
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (notificationManager.getCurrentInterruptionFilter() ==
                    NotificationManager.INTERRUPTION_FILTER_NONE) {
                return false;
            }
        }

        // 检查静音模式
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        return audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT;
    }

    /**
     * 请求音频焦点
     */
    private static void requestAudioFocus(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        AudioAttributes playbackAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
                .setAudioAttributes(playbackAttributes)
                .setAcceptsDelayedFocusGain(true)
                .setWillPauseWhenDucked(true)
                .build();

        audioManager.requestAudioFocus(focusRequest);
    }

    /**
     * 额外确保声音播放（针对某些厂商ROM）
     */
    private static void ensureSoundPlayback(Context context, @RawRes int soundResId) {
        try {
            Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + soundResId);
            Ringtone ringtone = RingtoneManager.getRingtone(context, soundUri);
            if (ringtone != null) {
                ringtone.play();
                // 3秒后自动停止，避免长时间播放
                new Handler().postDelayed(ringtone::stop, 3000);
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to ensure sound playback", e);
        }
    }

    /**
     * 生成唯一ID
     */
    private static int generateUniqueId() {
        return (int) System.currentTimeMillis();
    }
}